package com.zjw.project.weixin.api.userInfo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjw.entity.po.WeiUsers;
import com.zjw.project.weixin.api.accessToken.AccessTokenRedis;
import com.zjw.project.weixin.util.WeixinUtil;
import com.zjw.service.WeiUsersService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class UserInfoUtils {

    /**Redis AccessToken解决方案*/
    @Autowired
    private AccessTokenRedis accessTokenRedis;

    /**WeiUsers业务逻辑*/
    @Autowired
    private WeiUsersService weiUsersService;

    /**
     1、根据openid 判断 wei_users表中是否存在数据
     如果不存在：
     2、根据openid 查询微信服务器API接口得到JSON对象
     3、根据JSON对象转换成WeiUsers对象
     4、进行weiUsers.insert(weiUsers);
     */
    public void userInfoService(String openid){
        //1 根据openid判断 wei_users表中是否存在数据
        WeiUsers weiUsers= weiUsersService.selectWeiUsersByOpenid(openid);
        if(weiUsers==null){
            // 2、根据openid 查询微信服务器API接口得到JSON对象
            JSONObject jsonObject= this.sendWeixinApiUserInfo(openid);
            //3 JSONObject变成WeiUsers对象
            WeiUsers weiUsers1= this.convertJSONObjectToWeiUsers(jsonObject);
            //4 进行weiUsers.insert(weiUsers);
            weiUsersService.insertSelective(weiUsers1);
        }else{
            log.info("用户信息已存在，什么业务都不处理..."+weiUsers.toString());
        }
    }




    private static String WEIXIN_URL_GET_USER_INFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    /**
     * 调用微信 获取用户基本信息 接口调用
     * 接口调用请求说明 http请求方式: GET
     */
    public JSONObject sendWeixinApiUserInfo(String openid){
        String url=WEIXIN_URL_GET_USER_INFO.replace("OPENID",openid).replace("ACCESS_TOKEN",accessTokenRedis.getAccessTokenVal());
        JSONObject jsonObject= WeixinUtil.httpRequest(url,"GET",null);
        log.info(jsonObject.toString());
        return jsonObject;
    }

    /**
     * 根据JSON对象转换成WeiUsers对象
     */
    public WeiUsers convertJSONObjectToWeiUsers(JSONObject jsonObject){
        ObjectMapper objectMapper=new ObjectMapper();
        //1种：
//        WeiUsers weiUsers=new WeiUsers();
//       weiUsers.setNickname(jsonObject.getString("nickname"));
//        ......
        // 2种： JSON对象直接通过方法反射成JAVA BEAN
        WeiUsers weiUsers= null;
        try {
            weiUsers = objectMapper.readValue(jsonObject.toString(), WeiUsers.class);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
        return weiUsers;
    }
}
